import { Injectable, Logger } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { Model, SortOrder } from 'mongoose';
import { WorkflowTemplate } from '../interfaces/workflow.interface';

@Injectable()
export class WorkflowService {
    private readonly logger = new Logger(WorkflowService.name);

    constructor(
        @InjectModel('WorkflowTemplate')
        private workflowModel: Model<WorkflowTemplate>
    ) { }

    // 创建工作流模板
    async createTemplate(template: Partial<WorkflowTemplate>): Promise<WorkflowTemplate> {
        const newTemplate = new this.workflowModel({
            ...template,
            createTime: new Date(),
            updateTime: new Date(),
            stats: { uses: 0, likes: 0, views: 0 }
        });
        return newTemplate.save();
    }

    // 更新工作流模板
    async updateTemplate(id: string, template: Partial<WorkflowTemplate>): Promise<WorkflowTemplate> {
        return this.workflowModel.findByIdAndUpdate(
            id,
            {
                ...template,
                updateTime: new Date()
            },
            { new: true }
        );
    }

    // 获取工作流模板列表
    async getTemplates(
        query: any = {},
        page = 1,
        pageSize = 12,
        sort: { [key: string]: SortOrder } = { updateTime: -1 }
    ) {
        try {
            // 添加默认查询条件
            const finalQuery = {
                isPublic: true,
                ...query
            };

            const [total, templates] = await Promise.all([
                this.workflowModel.countDocuments(finalQuery),
                this.workflowModel
                    .find(finalQuery)
                    .sort(sort)
                    .skip((page - 1) * pageSize)
                    .limit(pageSize)
                    .select('name description thumbnail author tags category stats createTime updateTime')
                    .lean()
                    .exec()
            ]);

            // 确保返回的数据格式正确
            const items = templates.map(template => ({
                id: template._id.toString(),
                name: template.name || '',
                description: template.description || '',
                thumbnail: template.thumbnail || '/default-template.jpg', // 添加默认图片
                author: template.author || '',
                tags: template.tags || [],
                category: template.category || '',
                stats: {
                    uses: template.stats?.uses || 0,
                    likes: template.stats?.likes || 0,
                    views: template.stats?.views || 0
                },
                updateTime: template.updateTime || template.createTime || new Date()
            }));

            this.logger.debug(`Found ${items.length} templates`);
            this.logger.debug('Sample template:', items[0]);

            return {
                items,
                pagination: {
                    total,
                    page: Number(page),
                    pageSize: Number(pageSize),
                    pages: Math.ceil(total / pageSize)
                }
            };
        } catch (error) {
            this.logger.error('Failed to get templates:', error);
            throw error;
        }
    }

    // 获取单个工作流模板
    async getTemplate(id: string): Promise<WorkflowTemplate> {
        return this.workflowModel.findById(id);
    }

    // 删除工作流模板
    async deleteTemplate(id: string): Promise<boolean> {
        const result = await this.workflowModel.deleteOne({ _id: id });
        return result.deletedCount > 0;
    }

    // 更新统计信息
    async updateStats(id: string, type: 'uses' | 'likes' | 'views'): Promise<void> {
        await this.workflowModel.updateOne(
            { _id: id },
            { $inc: { [`stats.${type}`]: 1 } }
        );
    }
} 